.extern __MTVEC
.section .text
.global reset_handler
reset_handler:
  	/* set mtvec */
	auipc	x10, 0x0	/* x10 the start postion of the text segment*/
	addi	x10, x10, -256
	ori	x10, x10, 0x1
	csrw	mtvec, x10

	/* set all registers to zero */
	mv	x1, x0
	mv  	x2, x1
	mv  	x3, x1
	mv  	x4, x1
	mv  	x5, x1
	mv  	x6, x1
	mv  	x7, x1
	mv  	x8, x1
	mv  	x9, x1
	//mv	x10, x1
	mv	x11, x1
	mv 	x12, x1
	mv 	x13, x1
	mv 	x14, x1
	mv 	x15, x1
	mv 	x16, x1
	mv 	x17, x1
	mv 	x18, x1
	mv 	x19, x1
	mv 	x20, x1
	mv 	x21, x1
	mv 	x22, x1
	mv 	x23, x1
	mv 	x24, x1
	mv 	x25, x1
	mv 	x26, x1
	mv 	x27, x1
	mv 	x28, x1
	mv 	x29, x1
	mv 	x30, x1
	mv 	x31, x1

/* redirects global variables */
#if 0
	/* a0 == x10 is text segment start addr*/
	la	a1, __got_addr_start
	la	a2, __got_addr_end
	add	a1, a0, a1
	add	a2, a0, a2
	beq 	a1, a2, redirect_got_end

redirect_got:
	lw	a3, 0(a1)
	add	a3, a3, a0
	sw	a3, 0(a1)
	addi	a1, a1, 4
	bne	a1, a2, redirect_got
redirect_got_end:

	fence.i
#endif

.option push
.option norelax
	la	gp, __global_pointer$	/* temporary address */
.option pop

  	/* clear BSS */
clear_bss:
	la	x26, _bss_start
	la	x27, _bss_end
	bge	x26, x27, zero_loop_end

zero_loop:
	sw	x0, 0(x26)
	addi	x26, x26, 4
	ble	x26, x27, zero_loop
zero_loop_end:

	/* stack initilization */
	la	sp, __sp

main_entry:
	la	a0, __heap_start
	la	a1, __heap_end
	sub	a1, a1, a0
	jal	x1, c_main  /* jump to C execution environment c_main(heap_addr, heap_size) */

1:
	wfi
	j	1b


